package com.example.fushuang.balabala.client;

import android.util.Log;

import com.example.fushuang.balabala.model.LiveHost;
import com.example.fushuang.balabala.model.RecommendEntry;
import com.example.fushuang.balabala.model.VideoDetail;
import com.example.fushuang.balabala.model.VideoUrl;
import com.google.gson.Gson;

import org.apache.commons.codec.digest.DigestUtils;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Set;
import java.util.TreeMap;

/**
 * Created by admin on 2016/10/13.
 */

public class ClientAPI {

    private static final String APP_KEY = "1d8b6e7d45233436";
    private static final String APP_SECRET = "FamGR6I1OwSutCZ2CelYQTJznz42c7sBbJcC0YxGXToV8j14uk1+3VvTFEbyBZeW";

    private static final String PLAYURL_APP_KEY = "4ebafd7c4951b366";
    private static final String PLAYURL_APP_SECRET = "8cb98205e9b2ad3669aad0fce12a4c13";
    private static final String TAG = "111111111111";

    //以后如果发现okHttp不好用,直接在这里替换就行了,数据处理逻辑不需要发生变化
    private static AbstractHttpUtil sHttpUtil = new OkHttpUtil();

    private ClientAPI() {
    }

    public static void getRecommendListJSONAsync() {
        String url = "http://app.bilibili.com/x/show/old?appkey=1d8b6e7d45233436";
        sHttpUtil.doGetDataAsync(url, new NetCallback() {
            @Override
            public void onSuccess(String url, int code, byte[] data) {
                if (code == 200 && data != null) {
                    try {
                        String s = new String(data, "UTF-8");
                        Gson gson = new Gson();
                        RecommendEntry recommendEntry = gson.fromJson(s, RecommendEntry.class);
                        EventBus.getDefault().post(recommendEntry);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public static void getLiveHostJSonAsync(){
        String url="http://live.bilibili.com/AppNewIndex/recommend?_device=android&_hwid=08141b9dc840b0e0&appkey=1d8b6e7d45233436&build=427000&mobi_app=android&platform=android&scale=xhdpi&sign=81186f294b15114b29abc67f9320d3af";

        sHttpUtil.doGetDataAsync(url, new NetCallback() {
            @Override
            public void onSuccess(String url, int code, byte[] data) {
                if (code==200&&data!=null){
                    try {
                        String s = new String(data, "UTF-8");
                        Gson gson = new Gson();
                        LiveHost liveHost = gson.fromJson(s, LiveHost.class);
                        String s1 = gson.toJson(liveHost);

                        EventBus.getDefault().post(liveHost);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public static void getVideoDetail(String aid) {
        String url = "https://app.bilibili.com/x/view";

        TreeMap<String, String> params = new TreeMap<>();
        params.put("aid", aid);
        params.put("plat", "0");
        url = appendParamsWithSign(url, params, APP_KEY, APP_SECRET);

        sHttpUtil.doGetDataAsync(url, new NetCallback() {
            @Override
            public void onSuccess(String url, int code, byte[] data) {
                if (code == 200) {
                    try {
                        String str = new String(data, "UTF-8");
                        Log.d(TAG, "onSuccess: str" + str);
                        JSONObject json = new JSONObject(str);
                        code = json.getInt("code");
                        if (code==0) {
                            Gson gson = new Gson();
                            VideoDetail videoDetail = gson.fromJson(json.toString(), VideoDetail.class);
                            EventBus.getDefault().post(videoDetail);
                        }

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });


    }

    public static void getPlayUrlAsync(String cid,int quality,String videoType){
        String url = "http://interface.bilibili.com/playurl";
        TreeMap<String, String> params = new TreeMap<>();
        params.put("cid", cid);
        params.put("quality", Integer.toString(quality));
        params.put("otype", "json");
        params.put("type", videoType);

        url = appendParamsWithSign(url, params, PLAYURL_APP_KEY, PLAYURL_APP_SECRET);
//        Log.d(TAG, "getPlayUrlAsync: ");
        sHttpUtil.doGetDataAsync(url, new NetCallback() {
            @Override
            public void onSuccess(String url, int code, byte[] data) {
                if (code==200) {
                    try {
                        String str = new String(data, "UTF-8");
                        Gson gson = new Gson();
                        VideoUrl videoUrl = gson.fromJson(str, VideoUrl.class);
                        EventBus.getDefault().post(videoUrl);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private static String appendParamsWithSign(String url,TreeMap<String, String> params,String appKey, String appSecret) {
        String ret = url;

        if (url != null && params != null && appSecret != null && appKey != null) {

            params.put("appkey", appKey);
            params.put("build", "420000");
            params.put("channel", "bili");
            params.put("mobi_app", "android");
            params.put("platform", "android");
            // TODO: 需要机型适配
            params.put("screen", "xxhdpi");
            params.put("ts", Long.toString(System.currentTimeMillis()));

            String sign = sign(params, appSecret);
            StringBuilder sb = new StringBuilder(url);
            sb.append('?');
            Set<String> keySet = params.keySet();
            try {
                for (String key : keySet) {
                    sb.append(key).append('=')
                            .append(URLEncoder.encode(params.get(key), "UTF-8"))
                            .append('&');
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            if (sb.length() > 0) {
                sb.append("sign=").append(sign);
            }

            ret = sb.toString();
        }

        return ret;
    }

    /**
     * 计算sign 数值,进行数字签名
     *
     * @param params
     * @param appSecret
     * @return
     */
    private static String sign(TreeMap<String, String> params, String appSecret) {
        String ret = null;
        if (params != null && appSecret != null) {
            StringBuilder sb = new StringBuilder();

            Set<String> keySet = params.keySet();
            for (String key : keySet) {
                // key=value&key=value
                try {
                    sb.append(key).append('=')
                            .append(URLEncoder.encode(params.get(key), "UTF-8"))
                            .append('&');
                } catch (UnsupportedEncodingException ex) {
                    ex.printStackTrace();
                }
            }
            // key=value&key=value&
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }

            sb.append(appSecret);

            String str = sb.toString();

            ret = DigestUtils.md5Hex(str);

        }
        return ret;
    }
}
